<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="85px"
    >
      <el-form-item label="文件组名称" prop="groupName">
        <ns-input
          v-model="queryParams.groupName"
          class="!w-240px"
          clearable
          placeholder="请输入文件组名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <ns-input
          v-model="queryParams.fileName"
          class="!w-240px"
          clearable
          placeholder="请输入文件名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" v-hasPermi="['develop:file:search']" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" v-hasPermi="['develop:file:search']" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap class="custom-wrap">
    <div class="handle-btns">
      <el-button type="primary" @click="addFileHandle()" v-hasPermi="['develop:file:create']"
        >新增</el-button
      >
      <el-button type="primary" @click="sortFileHandle" v-hasPermi="['develop:file:sort']"
        >文件排重</el-button
      >
      <el-button type="primary" @click="downloadFiles">导出</el-button>
      <el-button type="primary" @click="suffixCheck">校验后缀</el-button>

      <el-dropdown v-hasPermi="['develop:file:sync']">
        <el-button type="primary" :icon="Refresh">引用文件</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="syncFile('1')">从文件服务器中引用</el-dropdown-item>
            <el-dropdown-item @click="syncFile('2')">从文件资产中引用</el-dropdown-item>
            <el-dropdown-item @click="syncFile('3')">从监测平台中引用</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div class="right-btn">
        <!-- <el-button type="primary" plain @click="multiEdit">编辑</el-button> -->
        <el-button type="danger" plain @click="multiDelete" v-hasPermi="['develop:file:delete']"
          >删除</el-button
        >
      </div>
    </div>
    <div class="file-tree-wrap">
      <el-auto-resizer>
        <template #default="{ height }">
          <el-tree-v2
            v-loading="loading"
            :data="list"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            show-checkbox
            :item-size="40"
            :height="height"
            :expand-on-click-node="true"
            @check-change="checkChange"
            ref="v2treeRef"
          >
            <template #default="{ node }">
              <el-icon v-if="node.data.type === 1" class="folder-icon"><Folder /></el-icon>
              <span class="node-item" :title="node.label">
                {{ node.label }}
                <span v-if="node.data.type === 1" class="pl-10px">
                  （归属机构:{{ node.data.deptName || '--' }}；
                </span>
                <span v-if="node.data.type === 1">
                  归属系统:{{ node.data.sysName || '--' }}）
                </span>
              </span>
              <div class="action-btns">
                <el-button
                  v-hasPermi="['develop:file:create']"
                  link
                  type="primary"
                  v-if="node.data.type === 1"
                  @click.stop="addFileHandle(node.key)"
                >
                  新增
                </el-button>
                <el-button
                  type="primary"
                  @click="copyFileHandle(node.data)"
                  link
                  v-hasPermi="['develop:file:copy']"
                  v-else
                  >复制</el-button
                >
                <el-button
                  v-hasPermi="['develop:file:issue']"
                  link
                  type="primary"
                  v-if="node.data.type !== 1"
                  @click.stop="issueFileHandle(node.key)"
                >
                  下发
                </el-button>
                <el-button
                  v-hasPermi="['develop:file:update']"
                  link
                  type="primary"
                  @click.stop="editFileDialogRef?.open([node.key], node.data.pid, node.data)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPermi="['develop:file:delete']"
                  link
                  type="danger"
                  @click.stop="handleDelete(node.data)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-tree-v2>
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>
  <SortFileDialog ref="sortFileDialogRef" :treeData="list" @success="getList" />
  <EditFileDialog ref="editFileDialogRef" @success="getList" />
  <CopyFileDialog ref="copyFileDialogRef" @success="getList" />
  <IssuaFileDialog ref="issueFileDialogRef" @success="getList" />
  <CheckSuffixDialog ref="checkSuffixDialogRef" :treeData="list" @success="getList" />
</template>

<script setup lang="ts">
import { Folder, Plus, Refresh } from '@element-plus/icons-vue'
import { getFileTree, deleteFile, multiDeleteFile } from '@/api/develop/file'
import SortFileDialog from './dialog/SortFile.vue'
import EditFileDialog from './dialog/EditFile.vue'
import CopyFileDialog from './dialog/CopyFile.vue'
import IssuaFileDialog from './dialog/IssuaFile.vue'
import CheckSuffixDialog from './dialog/CheckSuffix.vue'

import { ElTreeV2 } from 'element-plus'
import { useEmitt } from '@/hooks/web/useEmitt'
import { fileExchange } from '@/api/infra/file'

defineOptions({ name: 'DevelopFile' })

const router = useRouter()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

useEmitt({
  name: 'addFileSuccess',
  callback: () => {
    getList()
  }
})

const queryFormRef = ref() // 搜索的表单
const sortFileDialogRef = ref<InstanceType<typeof SortFileDialog>>()
const editFileDialogRef = ref<InstanceType<typeof EditFileDialog>>()
const copyFileDialogRef = ref()
const issueFileDialogRef = ref()
const checkSuffixDialogRef = ref()

const v2treeRef = ref<InstanceType<typeof ElTreeV2>>()

const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  groupName: '',
  fileName: ''
})

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFileTree(toRaw(queryParams))
    list.value = data
    v2treeRef?.value?.setCheckedKeys([])
  } finally {
    loading.value = false
  }
}

//校验文件后缀
const suffixCheck = async () => {
  checkSuffixDialogRef.value?.open()
}

onMounted(() => {
  getList()
})

/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    if (row.type == 1 && row.children?.length > 0) {
      // 删除的二次确认
      await message.confirm('确认删除该文件夹？删除文件夹会同时删除文件夹下所有文件')
    } else {
      // 删除的二次确认
      await message.delConfirm()
    }
    // 发起删除
    await deleteFile(row.id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 新增文件 */
function addFileHandle(pid?: string | number) {
  const path = pid ? `/develop/data-character/add-file/${pid}` : '/develop/data-character/add-file'
  jumpTo(path)
}

const downloadFiles = (e) => {
  const checkeds = v2treeRef.value?.getCheckedNodes()
  if (!checkeds || checkeds.length === 0) {
    message.confirm('请选择需要导出的文件')
    return
  }
  checkeds.forEach((item) => {
    if (item.path) {
      getFilePath(item)
    }
  })
}
//复制文件
const copyFileHandle = (row) => {
  copyFileDialogRef.value.open(row)
}

//下发文件
const issueFileHandle = (id) => {
  issueFileDialogRef.value.open(id)
}

// 获取文件下载地址
const getFilePath = async (row) => {
  const fileUrl = row.path
  const fileName = row.name
  const data = await fileExchange(fileUrl)
  fetch(data)
    .then((response) => {
      if (!response.ok) {
        throw new Error('文件未保存或已被清理')
      }
      return response.blob()
    })
    .then((blob) => {
      if (blob.type == 'application/json') {
        blob.text().then(() => {
          message.error('文件未保存或已被清理')
        })
      } else {
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(url)
      }
    })
    .catch((error) => {
      console.error('下载失败:', error)
    })
  // window.open(data)
}

/** 批量删除 */
async function multiDelete() {
  const checkedIds = v2treeRef.value?.getCheckedNodes().map((item) => item.id)
  if (!checkedIds || checkedIds.length === 0) {
    await message.confirm('请选择需要删除的文件')
    return
  }
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await multiDeleteFile(checkedIds as string[])
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
/** 批量编辑 */
async function multiEdit() {
  const checkedIds = v2treeRef.value?.getCheckedNodes().map((item) => item.id)

  if (!checkedIds || checkedIds.length === 0) {
    await message.confirm('请选择需要编辑的文件')
    return
  }

  editFileDialogRef.value?.open(checkedIds)
}

/** 文件排重 */
async function sortFileHandle() {
  const checkedRows = v2treeRef.value?.getCheckedNodes().filter((item) => item.type === 2)
  console.log('checkedRows', checkedRows)
  if (!checkedRows || checkedRows.length <= 1) {
    await message.confirm('请至少选择两个文件')
    return
  }
  sortFileDialogRef.value?.open(checkedRows)
}

/** 跳转路由 */
function jumpTo(path: string) {
  router.push(path)
}

/** 同步文件跳转 */
function syncFile(type: '1' | '2' | '3') {
  router.push({
    name: 'SyncFileForm',
    params: {
      type
    }
  })
}
</script>

<style lang="scss" scoped>
.handle-btns {
  margin-bottom: 20px;
  display: flex;
  :deep(.el-dropdown) {
    margin-left: 12px;
  }
  .right-btn {
    margin-left: auto;
  }
}
.custom-wrap {
  height: calc(100vh - 330px);
  :deep(.el-card__body) {
    height: 100%;
    & > div {
      height: 100%;
    }
  }
}
.file-tree-wrap {
  height: calc(100% - 100px);
  .node-item {
    font-size: 16px;
    flex: 1;
    max-width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .action-btns {
    padding-right: 20px;
    margin-left: auto;
  }
  .folder-icon {
    margin-right: 7px;
  }
  :deep(.el-tree-node__content) {
    .el-tree-node__expand-icon {
      font-size: 16px;
    }
    & > .el-checkbox {
      margin-right: 38px;
    }
  }
}
</style>
